package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.IssueSupplyUserDao;
import com.kly.user.db.dao.UserConversationDao;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.IssueSupplyUserEntity;
import com.kly.user.db.entity.UserEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;

/**
 * 下发补给用户池添加用户
 */
@Component
public class IssueSupplyUserTask {

    private static Log logger = LogFactory.getLog(IssueSupplyUserTask.class);

    @Resource
    private IssueSupplyUserDao issueSupplyUserDao;

    @Resource
    private UserDao userDao;

    @Resource
    private UserConversationDao userConversationDao;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();


//    @Scheduled(fixedDelay = 60000 * 5)
    public void execute() {
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, -5);
        List<UserEntity> userOnlineList = userDao.queryUserOnlineByCreatDate(nowTime.getTime());
        for (UserEntity userEntity : userOnlineList) {
            int todayConversationCount = userConversationDao.getUserTodayConversationCount(userEntity.getUserCode());
            if (todayConversationCount < 10) {
                IssueSupplyUserEntity issueSupplyUserEntity = new IssueSupplyUserEntity();
                issueSupplyUserEntity.setUserCode(userEntity.getUserCode());
                issueSupplyUserEntity.setGender(userEntity.getGender());
                issueSupplyUserEntity.setConnectCount(todayConversationCount);
                issueSupplyUserEntity.setUseStatus(0);
                issueSupplyUserDao.insert(issueSupplyUserEntity);
            }
        }
        if (!userOnlineList.isEmpty()) {
            //删除所有状态为1的数据
            issueSupplyUserDao.deleteNotUse();
            //更新状态为1
            issueSupplyUserDao.updateUseStatus();
        }
    }

}
